import json


from constr_budgets.models import Project, People, Modules,Templates,Day,Record,Place,Remarks
from django.http import JsonResponse
from django.views import View


# 项目数据接口
class Projects(View):
    def get(self, request):
        d = request.GET.get("id")
        if d is None:
            da = Project.objects.all().values("id", "name", "square", "templates_id", "createTime", "templates_id__name")
            for dda in da:
                aimlist = Place.objects.filter(template_id=dda['templates_id'],).values()
                add = 0
                for ai in aimlist:
                    add += ai['square']
                dda['square'] = add
            return JsonResponse({
                'code': 200,
                'data': list(da)
            })
        else:
            try:
                da = list(People.objects.filter(id=d).values())[0]
                dict1 = eval(da["role_auth"]).keys()
                pro = []
                if len(dict1) == 0:
                    return JsonResponse({"code": 201, "msg": "该用户没有分配项目"})
                for i in dict1:
                    if(list(Project.objects.filter(id=i).values())):
                        pro.append(list(Project.objects.filter(id=i).values())[0])
                    # else:
                    #     return JsonResponse({"code": 201, "msg": "该用户没有分配项目"})
                return JsonResponse({
                    'code': 200,
                    'data': pro
                })
            except TypeError:
                return JsonResponse({"code": 201, "msg": "暂无权限"})

    def post(self, request):
        data = json.loads(request.body)
        print(data)
        # try:
        aimProject = Project.objects.create(name=data['name'], templates_id=data['models'])
        aimTemplate = Templates.objects.get(id=data['models'])
        placelist = list(aimTemplate.place_set.all().values())
        moduleslist = list(aimTemplate.modules_set.all().values())
        aimtime = Day.objects.filter(time=aimProject.createTime)  # 该项目时间
        aimtime = aimtime[0]
        print(aimtime)
        for i in moduleslist:
            Remarks.objects.create(remark="", day_id=aimtime.id, modules_id=i['id'], project_id=aimProject.id)
            for j in placelist:
                if not Record.objects.filter(modules=i['id']).filter(place=j['id']).filter(project_id=aimProject.id).filter(day_id=aimtime.id):
                    newRecoder =Record.objects.create(project_id=aimProject.id,day_id=aimtime.id)
                    newRecoder.modules.add(i['id'])
                    newRecoder.place.add(j['id'])
        # except:
        #     return JsonResponse({
        #         'code': 400,
        #         'message': '项目名称不可以重复',
        #     })
        return JsonResponse({
            'code': 200,
            'message': '添加项目成功',
        })

    def put(self, request):
        data = json.loads(request.body)
        Project.objects.filter(id=data['id']).update(name=data['name'])
        return JsonResponse({
            'code': 200,
            "message": "修改项目信息成功"
        })

    def delete(self, request):
        d = request.GET.get("id")
        Project.objects.filter(id=d).delete()
        return JsonResponse({
            'code': 200,
            "message": "删除项目信息成功"
        })

    def patch(self, request):
        d = request.GET.get("id")
        pro_id = request.GET.get("pro_id")
        project = list(Project.objects.filter(id=pro_id).values('templates_id'))[0]
        template_id = project['templates_id']
        placeList = list(Place.objects.filter(template_id=template_id).values('id', 'name', 'square'))
        try:
            da = list(People.objects.filter(id=d).values())[0]
            dict1 = eval(da["role_auth"])
            li = []
            auth = dict1[int(pro_id)]
            for i in auth:
                li.append(list(Modules.objects.filter(id=i).values())[0])
            return JsonResponse({"code": 200, "msg": "请求成功", "data": {"place": placeList, 'modules': li}})
        except TypeError:
            return JsonResponse({"code": 201, "msg": "暂无权限"})
        except KeyError:
            return JsonResponse({"code": 202, "msg": "暂无分配"})
